package com.focus.wecenter.service.impl;

import com.focus.wecenter.dao.UserDao;
import com.focus.wecenter.pojo.User;
import com.focus.wecenter.web.vo.SearchResult;
import com.focus.wecenter.dao.QuestionDao;
import com.focus.wecenter.dao.TopicDao;
import com.focus.wecenter.pojo.Question;
import com.focus.wecenter.pojo.Topic;
import com.focus.wecenter.service.QuestionService;
import com.focus.wecenter.util.Message;
import com.focus.wecenter.util.PageBean;
import com.focus.wecenter.web.vo.QuestionPublishForm;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 问题模块页面实现
 *
 * @author Lv Jing
 * @date 2018年01月06日 17:33
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private TopicDao topicDao;
    @Autowired
    private UserDao userDao;

    @Override
    public Question publishQuestion(QuestionPublishForm questionPublishForm) {
        // 关联用户
        User user = userDao.findById(Integer.parseInt(questionPublishForm.getAsk_user_id()));
        user.setIntegral(user.getIntegral() + 10);
        user.setQuestionCount(user.getQuestionCount() + 1);
        // 添加话题到数据库
        List<Topic> topics = new ArrayList<>();
        // 1.先检查当前话题是否已存在
        for (String topicName : questionPublishForm.getTopics()) {
            Topic topic = topicDao.findByTopicName(topicName);
            if (topic == null) {
                // 2.不存在则添加到数据库
                topic = new Topic();
                topic.setTopicName(topicName);
                topic.setUser(user);
                topic.setDiscussCount(1);
                topic.setTopicPic("");
                topicDao.add(topic);
            }
            // 3.把话题保存到临时的话题集合
            topics.add(topic);
        }

        // 添加问题
        Question question = new Question();
        question.setUser(user);
        question.setContent(questionPublishForm.getContent());
        question.setTitle(questionPublishForm.getTitle());
        question.setCategory(questionPublishForm.getCategory());
        questionDao.add(question);

        // 问题与话题之间关系连接 FIXME:问题与话题只级联一边
        for (Topic topic : topics) {
            topic.getInvolveQuestions().add(question);
        }
        // question.setInvolvedTopics(new HashSet<>(topics));
        return question;
    }

    @Override
    public PageBean<Question> findQuestionByPage(int currentPage, int pageSize) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
        criteria.addOrder(Order.desc("updateTime"));
        return questionDao.findByPage(criteria, currentPage, pageSize);
    }

    @Override
    public Question findQuestionByID(int questionID) {
        return questionDao.findById(questionID);
    }

    @Override
    public Message focus(int questionID, int userID) {
        Message message = new Message();
        if (userID == -1) {
            message.setSuccess(false);
            message.setData("请先登录");
            return message;
        }
        // 查找用户
        User user = userDao.findById(userID);
        if (user == null) {
            message.setSuccess(false);
            message.setData("请先登录");
            return message;
        }
        // 查找问题
        Question question = questionDao.findById(questionID);
        if (question == null) {
            message.setSuccess(false);
            message.setData("问题不存在");
            return message;
        }
        // 判断用户是否关注该问题
        if (user.getFocusQuestions().contains(question)) {
            // 关注了就取关
            user.getFocusQuestions().remove(question);
            question.setConcernNumber(question.getConcernNumber() - 1);
            message.setSuccess(true);
            message.setData("remove");
            return message;
        }
        // 用户与问题关联
        user.getFocusQuestions().add(question);
        question.setConcernNumber(question.getConcernNumber() + 1);
        message.setSuccess(true);
        message.setData("add");
        return message;
    }

    @Override
    public boolean isFocus(int questionID, int userID) {
        User user = userDao.findById(userID);
        if (user == null) {
            return false;
        }
        Question question = new Question();
        question.setId(questionID);
        return user.getFocusQuestions().contains(question);
    }

    @Override
    public List<SearchResult> searchQuestion(String query, int limit) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
        criteria.add(Restrictions.like("title", query, MatchMode.ANYWHERE).ignoreCase());
        PageBean<Question> pageResult = questionDao.findByPage(criteria, 1, limit);
        List<SearchResult> results = new ArrayList<>();
        for (Question question : pageResult.getList()) {
            SearchResult result = new SearchResult();
            result.setId(question.getId());
            result.setContent(question.getTitle());
            result.setType("questions");
            result.put("answer_count", question.getAnswerCount());
            results.add(result);
        }
        return results;
    }

    @Override
    public PageBean<Question> findByPage(DetachedCriteria criteria, int currentPage, int pageSize) {
        if (currentPage == 0) {
            currentPage = 1;
        }
        return questionDao.findByPage(criteria, currentPage, pageSize);
    }

    @Override
    public List<Question> findByPageWithList(DetachedCriteria criteria, int currentPage, int pageSize) {
        return questionDao.findPage(criteria, currentPage, pageSize);
    }
}
